package logic

import (
	"context"
	"fmt"
	"hotel/model/mysql"
	"hotel/model/redis"

	"hotel/hotelrpc/hotelrpc"
	"hotel/hotelrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *hotelrpc.LoginRequest) (*hotelrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Rdb.Get("sendSmslogin" + in.Phone)
	if get.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("手机号验证码错误")
	}

	var hotel mysql.Hotel
	mysql.DB.Where("phone = ?", in.Phone).Find(&hotel)
	if hotel.Phone == "" {
		return nil, fmt.Errorf("账号未注册，请前往注册")
	}
	if hotel.Password != in.Password {
		return nil, fmt.Errorf("密码错误")
	}
	mysql.DB.Debug().Find(&hotel)
	redis.Rdb.Del("sendSmslogin" + in.Phone)
	return &hotelrpc.LoginResponse{Id: int64(hotel.ID)}, nil
}
